<?php
declare(strict_types=1);

namespace app\common\utils;

use app\common\enum\ResponseCode;
use think\response\Json;

class JsonResponse
{
    /**
     * 成功响应
     * @param mixed $data 响应数据
     * @param string $msg 响应信息
     * @param int $code 响应码
     * @return Json
     */
    public static function success($data = null, string $msg = '', int $code = ResponseCode::SUCCESS): Json
    {
        $msg = $msg ?: ResponseCode::$messages[ResponseCode::SUCCESS];
        
        return json([
            'code' => $code,
            'msg' => $msg,
            'data' => $data
        ]);
    }
    
    /**
     * 错误响应
     * @param string $msg 错误信息
     * @param int $code 错误码
     * @param mixed $data 响应数据
     * @return Json
     */
    public static function error(string $msg = '', int $code = ResponseCode::BAD_REQUEST, $data = null): Json
    {
        if (empty($msg) && isset(ResponseCode::$messages[$code])) {
            $msg = ResponseCode::$messages[$code];
        }
        
        return json([
            'code' => $code,
            'msg' => $msg,
            'data' => $data
        ]);
    }

    /**
     * 自定义返回
     * @param int $code 状态码
     * @param string $msg 提示信息
     * @param mixed $data 返回数据
     * @return \think\response\Json
     */
    public static function result(int $code, string $msg, $data = null)
    {
        return json([
            'code' => $code,
            'msg'  => $msg,
            'data' => $data
        ]);
    }

    /**
     * 返回分页数据
     * @param mixed $list 分页数据
     * @param string $msg 提示信息
     * @param int $code 状态码
     * @return \think\response\Json
     */
    public static function successPaginate($list, string $msg = '', int $code = ResponseCode::SUCCESS)
    {
        $msg = $msg ?: ResponseCode::$messages[ResponseCode::SUCCESS];

        return json([
            'code' => $code,
            'msg'  => $msg,
            'data' => [
                'list' => $list->items(),
                'total' => $list->total(),
                'page' => $list->currentPage(),
                'page_size' => $list->listRows()
            ]
        ]);
    }
} 